<template>
  <div class="user-list-container">
    <!-- 页面标题 -->
    <div class="header-title">组织管理</div>

    <!-- 查询与筛选区域 -->
    <el-form :inline="true" class="filter-form" size="small">
      <el-input
        v-model="search.DepartmentName"
        placeholder="部门名称"
        style="width: 200px; margin-right: 8px"
      />
      <el-button type="primary" @click="getDepartmentTree">查询</el-button>
      <el-button @click="ResetInfo">重置</el-button>
    </el-form>

    <!-- 操作按钮 -->
    <div class="action-btns" style="margin-bottom: 16px">
      <el-button type="primary" @click="openNewDeptDialog">新建部门</el-button>
      <el-button>添加标签</el-button>
      <el-button>导出数据</el-button>
      <el-button @click="toggleAllRows(false)" style="float: right"
        >全部折叠</el-button
      >
      <el-button
        @click="toggleAllRows(true)"
        style="float: right; margin-right: 8px"
        >全部展开</el-button
      >
    </div>

    <!-- 部门数据表格 -->
    <el-table
      ref="tableRef"
      :data="tableData1"
      style="width: 100%"
      row-key="departmentId"
      border
      lazy
      :load="load"
      :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
    >
      <el-table-column prop="departmentName" label="部门名称" width="150" />
      <el-table-column prop="departmentStatus" label="状态" width="100">
        <template #default="scope">
          <span class="status-dot">
            <span v-if="scope.row.departmentStatus == 0">
              <span class="dot"></span>启用
            </span>
            <span v-else> <span class="dot2"></span>禁用 </span>
          </span>
        </template>
      </el-table-column>
      <el-table-column prop="memberNumber" label="成员数量" width="100" />
      <el-table-column prop="governor" label="主管人员" width="100" />
      <el-table-column prop="departmentDesc" label="部门描述" />
      <el-table-column prop="createTime" label="更新时间" width="160">
        <template #default="scope">
          <span>{{
            moment(scope.row.createTime).format("YYYY-MM-DD hh:mm:ss")
          }}</span>
        </template>
      </el-table-column>
      <el-table-column type="index" label="排序" width="80" />
      <el-table-column label="操作" width="240">
        <template #default="scope">
          <el-button
            type="primary"
            plain
            size="small"
            @click="openEditDeptDialog(scope.row)"
            >编辑</el-button
          >
          <el-button
            type="primary"
            plain
            size="small"
            @click="openStatusDialog(scope.row)"
            >设置状态</el-button
          >
          <el-button
            type="danger"
            plain
            size="small"
            @click="DeptDelete(scope.row.departmentId)"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <!-- 设置状态模态框 -->
    <el-dialog
      title="设置状态"
      v-model="statusDialogVisible"
      width="30%"
      @close="resetStatusDialog"
    >
      <!-- 模态框内容 -->
      <el-form :model="currentDept" label-width="100px">
        <el-form-item label="选择部门">
          <!-- 这里可以放部门选择的输入框或选择器 -->
          <!-- 根据图片，这里可能是一个部门名称的展示或者选择器 -->
          <el-input v-model="currentDept.departmentName" disabled></el-input>
        </el-form-item>
        <el-form-item label="选择状态">
          <el-radio-group v-model="currentDept.departmentStatus">
            <el-radio-button :label="0">启用</el-radio-button>
            <el-radio-button :label="1">禁用</el-radio-button>
          </el-radio-group>
        </el-form-item>
      </el-form>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="statusDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="saveStatus">保存</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 新建部门对话框 -->
    <el-dialog
      title="新建部门"
      v-model="newDeptDialogVisible"
      width="30%"
      @close="resetNewDeptForm"
    >
      <!-- 表单内容 -->
      <el-form
        :model="newDeptForm"
        :rules="newDeptRules"
        ref="newDeptFormRef"
        label-width="100px"
      >
        <el-form-item label="部门名称" prop="departmentName" required>
          <el-input
            v-model="newDeptForm.departmentName"
            placeholder="请输入内容"
          ></el-input>
        </el-form-item>
        <!-- 新增状态字段 -->
        <el-form-item label="状态" required>
          <el-radio-group v-model.number="newDeptForm.departmentStatus">
            <el-radio-button :label="0">启用</el-radio-button>
            <el-radio-button :label="1">禁用</el-radio-button>
          </el-radio-group>
        </el-form-item>
        <!-- 新增成员数量字段 -->
        <el-form-item label="成员数量">
          <el-input-number v-model.number="newDeptForm.memberNumber" :min="0" />
        </el-form-item>
        <el-form-item label="上级部门">
          <el-cascader
            v-model="newDeptForm.parentId"
            :options="options"
            :props="props"
            style="width: 600px"
          />
        </el-form-item>
        <el-form-item label="主管人员" prop="governor" required>
          <el-input
            v-model="newDeptForm.governor"
            placeholder="请选择人员"
          ></el-input>
        </el-form-item>
        <el-form-item label="部门描述">
          <el-input
            type="textarea"
            v-model="newDeptForm.departmentDesc"
            placeholder="请输入内容"
            maxlength="100"
            show-word-limit
          ></el-input>
        </el-form-item>
      </el-form>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="newDeptDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="saveNewDept">保存</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 编辑部门对话框 -->
    <el-dialog
      title="编辑部门"
      v-model="editDeptDialogVisible"
      width="30%"
      @close="resetEditDeptForm"
    >
      <!-- 表单内容 -->
      <el-form
        :model="editDeptForm"
        :rules="editDeptRules"
        ref="editDeptFormRef"
        label-width="100px"
      >
        <el-form-item label="部门名称" prop="departmentName" required>
          <el-input
            v-model="editDeptForm.departmentName"
            placeholder="请输入内容"
          ></el-input>
        </el-form-item>
        <el-form-item label="上级部门">
          <!-- 这里需要一个选择器来选择上级部门，暂时使用输入框代替 -->
          <el-cascader
            v-model="editDeptForm.parentId"
            :options="options"
            :props="props"
            style="width: 600px"
          />
        </el-form-item>
        <el-form-item label="主管人员" prop="governor" required>
          <!-- 这里需要一个选择器来选择主管人员，暂时使用输入框代替 -->
          <el-input
            v-model="editDeptForm.governor"
            placeholder="请选择人员"
          ></el-input>
        </el-form-item>
        <el-form-item label="部门描述">
          <el-input
            type="textarea"
            v-model="editDeptForm.departmentDesc"
            placeholder="请输入内容"
            maxlength="100"
            show-word-limit
          ></el-input>
        </el-form-item>
      </el-form>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="editDeptDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="saveEditDept">保存</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { onMounted, reactive, ref, watch } from "vue";
import { DeleteDept, GetDept, UpdateDeptStatus, GetDeptByParentId, AddDept, UpdateDept } from "@/Api/dept";
import moment from "moment";
import { ElMessageBox, ElMessage, ElInputNumber } from 'element-plus'
import type { FormInstance, FormRules } from 'element-plus'

// 控制新建部门对话框的显示隐藏
const newDeptDialogVisible = ref(false);

// 新建部门表单ref
const newDeptFormRef = ref<FormInstance>()

// 新建部门表单
const newDeptForm = reactive({
    departmentName: '',
    parentId: '',
    governor: '',
    departmentDesc: '',
    departmentStatus: 0,
    memberNumber: 0
});

// 新建部门表单校验规则
const newDeptRules = reactive<FormRules>({
    departmentName: [
        { required: true, message: '请输入部门名称', trigger: 'blur' }
    ],
    governor: [
        { required: true, message: '请选择主管人员', trigger: 'blur' }
    ],
    departmentStatus: [
        { required: true, message: '请选择状态', trigger: 'change' }
    ],
})

// 打开新建部门对话框
const openNewDeptDialog = () => {
    newDeptDialogVisible.value = true;
    GetDeptById();
};

// 关闭新建部门对话框时重置表单和校验状态
const resetNewDeptForm = () => {
    newDeptForm.departmentName = '';
    newDeptForm.parentId = '';
    newDeptForm.governor = '';
    newDeptForm.departmentDesc = '';
    newDeptForm.departmentStatus = 0;
    newDeptForm.memberNumber = 0;
    if (newDeptFormRef.value) {
        newDeptFormRef.value.resetFields(); // 重置表单校验状态
    }
};

// 保存新建部门
const saveNewDept = async () => {
    if (!newDeptFormRef.value) return;

    newDeptFormRef.value.validate(async (valid) => {
        if (valid) {
            //调用后端接口保存新建部门
            const response = await AddDept(newDeptForm);
            // 根据实际后端返回判断是否成功，这里简单判断
            if (response.data && response.data.code === 200) { // 假设后端成功返回code为200
                ElMessage.success("新增部门成功!");
                newDeptDialogVisible.value = false;
                getDepartmentTree(); // 刷新列表
            } else {
                ElMessage.error("新增部门失败，请重试!"); // 或者显示后端返回的错误信息
            }
        } else {
            console.log('表单校验失败');
        }
        return; // 显式返回 void
    });
};

// 控制设置状态模态框的显示隐藏
const statusDialogVisible = ref(false);

// 当前编辑的部门信息
const currentDept = reactive({
    DepartmentId: '',
    departmentName: '',
    departmentStatus: ''
});

// 打开设置状态模态框
const openStatusDialog = (row: any) => {
    statusDialogVisible.value = true;
    currentDept.DepartmentId = row.departmentId;
    currentDept.departmentName = row.departmentName;
    currentDept.departmentStatus = row.departmentStatus;
};

// 关闭设置状态模态框时重置数据
const resetStatusDialog = () => {
    currentDept.DepartmentId = '';
    currentDept.departmentName = '';
    currentDept.departmentStatus = '';
};

// 保存状态
const saveStatus = async () => {
    var params = {
        DepartmentId: currentDept.DepartmentId,
        status: currentDept.departmentStatus
    }
    console.log(params);

    await UpdateDeptStatus(params)
    ElMessage.success("保存成功!")
    statusDialogVisible.value = false;
    getDepartmentTree();
};

// 控制编辑部门对话框的显示隐藏
const editDeptDialogVisible = ref(false);

// 编辑部门表单ref
const editDeptFormRef = ref<FormInstance>()

// 编辑部门表单
const editDeptForm = reactive({
    departmentId: '',
    departmentName: '',
    parentId: '',
    governor: '',
    departmentDesc: '',
});

// 编辑部门表单校验规则
const editDeptRules = reactive<FormRules>({
    departmentName: [
        { required: true, message: '请输入部门名称', trigger: 'blur' }
    ],
    governor: [
        { required: true, message: '请选择主管人员', trigger: 'blur' }
    ]
})

// 打开编辑部门对话框
const openEditDeptDialog = (row: any) => {
    editDeptDialogVisible.value = true;
    console.log(row);

    // 填充表单数据
    editDeptForm.departmentId = row.departmentId;
    editDeptForm.departmentName = row.departmentName;
    editDeptForm.parentId = row.parentId; // 需要根据实际数据结构调整
    editDeptForm.governor = row.governor; // 需要根据实际数据结构调整
    editDeptForm.departmentDesc = row.departmentDesc; // 需要根据实际数据结构调整
};

// 关闭编辑部门对话框时重置表单和校验状态
const resetEditDeptForm = () => {
    editDeptForm.departmentId = '';
    editDeptForm.departmentName = '';
    editDeptForm.parentId = '';
    editDeptForm.governor = '';
    editDeptForm.departmentDesc = '';
    if (editDeptFormRef.value) {
        editDeptFormRef.value.resetFields();
    }
};

// 保存编辑部门（待实现）
const saveEditDept = async () => {
    if (!editDeptFormRef.value) return;

    editDeptFormRef.value.validate(async (valid) => {
        if (valid) {
            console.log("保存编辑的部门信息:", editDeptForm);
            // 调用后端接口保存编辑后的部门信息
            const response = await UpdateDept(editDeptForm);
            if (response.data && response.data.code === 200) {
                ElMessage.success("部门信息更新成功!");
                editDeptDialogVisible.value = false;
                getDepartmentTree(); // 刷新列表
            } else {
                ElMessage.error("部门信息更新失败，请重试!");
            }
        } else {
            console.log('表单校验失败');
        }
        return;
    });
};

//删除部门
const DeptDelete = async (id: any) => {
    ElMessageBox.confirm(
        '确定要删除该部门吗？此操作不可撤销！',
        '提示',
        {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
        }
    ).then(async () => {
        // 调用后端接口删除
        await DeleteDept(id)
        ElMessage.success('删除成功！')
        getDepartmentTree()
    }).catch(() => {
        // 用户取消，无需处理
    })
}

interface Dept {
    departmentId: number
    departmentName: string
    departmentStatus: number
    memberNumber: number
    governor: string
    departmentDesc: string
    createTime:Date
    hasChildren?: boolean
    children?: Dept[]
  }


  const load = (
    row: Dept,
    treeNode: unknown,
    resolve: (data: Dept[]) => void
  ) => {
    setTimeout(() => {
      if (row.departmentId === 1) {
        resolve([

        ])
      } else {
        resolve([])
      }
    }, 1000)
  }

    // 获取部门树形数据的API函数
    const getDepartmentTree = async () => {
    try {
        var params={
            parentid: 0,
            DepartmentName:''
        }
       const response = await GetDept(params)
       tableData1.value = response.data.data
      console.log(response);

    } catch (error) {
      console.error('获取部门树形数据失败:', error)
    }
  }

    // 初始根节点数据
    const tableData1=ref([])




//查询条件信息
const search = reactive({
    DepartmentName: "",
});

//重置查询条件
const ResetInfo = () => {
    search.DepartmentName = ""
    getDepartmentTree();
}


const onSelectionChange = (val: any) => {
    // 多选逻辑
}


///级联选择器配置
const props = {
    checkStrictly: true,
    emitPath: false
}

//级联选择器数据
const options = ref([])

//级联获取部门信息
const GetDeptById = async () => {
    const response = await GetDeptByParentId()
    console.log(response);
    options.value = response.data.data
}

// 添加表格引用
const tableRef = ref()

// 添加展开/折叠方法
const toggleAllRows = (isExpand: boolean) => {
  if (!tableRef.value) return

  const processNodes = (nodes: any[]) => {
    nodes.forEach((row: any) => {
      // 调用 toggleRowExpansion 方法
      tableRef.value.toggleRowExpansion(row, isExpand)

      // 如果节点有子节点，递归处理子节点
      if (row.children && row.children.length > 0) {
        processNodes(row.children)
      }
    })
  }

  // 从根节点开始处理
  processNodes(tableData1.value)
}

  // 页面加载时获取数据
  onMounted(() => {
    getDepartmentTree()
  })
</script>

<style scoped>
.user-list-container {
  background: #fff;
  padding: 2% 3%;
  border-radius: 0.5em;
}

.header-title {
  font-size: 1.3em;
  font-weight: bold;
  margin-bottom: 2%;
}

.filter-form {
  margin-bottom: 1.5%;
}

.action-btns {
  margin-bottom: 1.5%;
}

.status-dot {
  display: flex;
  align-items: center;
  font-size: 15px;
}

.status-dot .dot {
  width: 8px;
  height: 8px;
  background: #13ce66;
  border-radius: 50%;
  display: inline-block;
  margin-right: 6px;
}

.status-dot .dot2 {
  width: 8px;
  height: 8px;
  background: red;
  border-radius: 50%;
  display: inline-block;
  margin-right: 6px;
}

.main-container {
  max-width: 100%;
  margin: 0 auto;
  width: 100%;
  /* 可根据需要加padding: 2% 3%; */
}

.detail-form .el-form-item__label {
  color: #666;
  font-weight: bold;
}

.el-table .el-table__cell {
  padding: 6px 8px !important;
  font-size: 14px;
}
</style>
